﻿using AMobiSDK;
using BaoVeBienCuong.SelectMap;
using BaoVeBienCuong.Store;
using BapVeBienCuong.menu;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using QStoreLibrary;
using System;
using System.Windows;
using System.Windows.Navigation;
namespace BaoVeBienCuong
{
    public partial class MainPage : PhoneApplicationPage
    {
        UIElementRenderer elementRenderer;
        public static ContentManager contentManager;
        public static DiemCao diemcao;
        GameTimer timer;
        SpriteBatch spriteBatch;
        ButtonMenu[] buttonMenu = new ButtonMenu[8];
        Vector2 start, curtouch;
        public static SaveMusic savemusic;
        Texture2D bg, bgThanhTich;
        SpriteFont font;
        static bool nhacnen;
        static bool nhacgame;
        private bool isCaiDat;
        private bool isInfor;
        private bool isThanhTich;
        public MainPage()
        {
            InitializeComponent();

            TouchPanel.EnabledGestures = GestureType.Tap;
            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
            savemusic = new SaveMusic();
            savemusic.readMusic();
        }
        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //if (!new AdManager().OnBackKeyPress(this, webBrowser1, e))
            {
                if (isThanhTich)
                {
                    isThanhTich = false;
                    e.Cancel = true;
                }
                else if (isCaiDat)
                {
                    CaiDatStoryboard2.Begin();
                    CaiDatStoryboard2.Completed += CaiDatStoryboard2_Completed;
                }
                else if (isInfor)
                {
                    PlayNhacGame("MapSelect", true);
                    inforStoryboard2.Begin();
                    inforStoryboard2.Completed += inforStoryboard2_Completed;
                }
                else
                {
                    MessageBoxResult m = MessageBox.Show("Bạn muốn thoát khỏi chương trình?", "", MessageBoxButton.OKCancel);
                    if (m == MessageBoxResult.OK)
                    {
                        // Application.Current.Terminate();
                        Microsoft.Xna.Framework.Game game = new Microsoft.Xna.Framework.Game();
                        game.Exit();
                    }
                }
            }
            e.Cancel = true;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            new CheckInstall().sendData(ContentPanel);
            inapp.show("left", 155, 15);
            if (SelectMapAndStore.contentManager != null)
            {
                SelectMapAndStore.contentManager.Unload();
            }
            Loading.contentManager.Unload();
            diemcao = new DiemCao();
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here

            // Start the timer
            timer.Start();

            AdManager.setWidgetCode("ef4b8505f8cb9dfc57191f853c3b970d");//chỉ cần gọi hàm setWidgetCode này một lần 
            //duy nhất trong toàn bộ Project
            AdManager advertisement = new AdManager();
            advertisement.OnNavigationTo(this, bannerFullScreen, banner300x250, banner320x50);

            for (int i = 0; i <= 7; i++)
            {
                buttonMenu[i] = new ButtonMenu(i);
                buttonMenu[i].setType(i);
                buttonMenu[i].Load(contentManager);
            }
            font = contentManager.Load<SpriteFont>("fonts/font1");
            savemusic = new SaveMusic();
            savemusic.readMusic();
            nhacgame = SaveMusic.nhacgame;
            nhacnen = SaveMusic.nhacnen;
            bg = contentManager.Load<Texture2D>("images/menu/menu");
            bgThanhTich = contentManager.Load<Texture2D>("images/menu/infoFrame");
            SetNhacButton();
            PlayNhacGame("MapSelect", true);

            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //savemusic.
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            TouchCollection touchs = TouchPanel.GetState();
            foreach (TouchLocation touch in touchs)
            {
                if (!isCaiDat && !isInfor && !isThanhTich)
                {
                    if (touch.State == TouchLocationState.Pressed)
                    {

                        start = touch.Position;
                        curtouch = touch.Position;
                    }
                    if (touch.State == TouchLocationState.Moved)
                    {
                        curtouch = touch.Position;
                        for (int i = 0; i <= 7; i++)
                        {
                            buttonMenu[i].isTouch(curtouch);
                        }
                    }
                    if (touch.State == TouchLocationState.Released)
                    {
                        for (int i = 0; i <= 7; i++)
                        {
                            if (buttonMenu[i].isTouch(curtouch))
                            {
                                switch (i)
                                {
                                    case 0:
                                        PlayHieuUng("Click", false);
                                        NavigationService.Navigate(new Uri("/SelectMap/SelectMapAndStore.xaml", UriKind.RelativeOrAbsolute));
                                        break;
                                    case 1:
                                        PlayHieuUng("Click", false);
                                        isCaiDat = true;

                                        CaiDatStoryboard1.Begin();
                                        break;
                                    case 2:
                                        PlayHieuUng("Click", false);
                                        isThanhTich = true;
                                        break;
                                    case 3:
                                        PlayHieuUng("Click", false);
                                        //MessageBox.Show("Chức năng đang được phát triển!");
                                        WebBrowserTask webBrowserTask = new WebBrowserTask();

                                        webBrowserTask.Uri = new Uri("http://w.qplay.vn/", UriKind.Absolute);

                                        webBrowserTask.Show();
                                        break;
                                    case 4:
                                        PlayHieuUng("Click", false);
                                        ShareLinkTask shareLinkTask = new ShareLinkTask();

                                        shareLinkTask.Title = "Loạn 12 sứ quân - Game Hot - Thủ thành tiếng Việt trên winphone";
                                        shareLinkTask.LinkUri = new Uri("http://www.windowsphone.com/en-us/store/app/lo%E1%BA%A1n-12-s%E1%BB%A9-qu%C3%A2n/1671d059-0330-43d3-9031-d48bbd4e9427", UriKind.Absolute);
                                        shareLinkTask.Message = "Tôi đang chơi game Loạn 12 sứ quân trên winphone, có bạn nào muốn chơi cùng không ?";

                                        shareLinkTask.Show();
                                        break;
                                    case 5:
                                        PlayHieuUng("Click", false);

                                        isInfor = true;

                                        inforStoryboard1.Begin();
                                        break;
                                    case 6:
                                        PlayHieuUng("Click", false);
                                        MessageBoxResult m = MessageBox.Show("Bạn muốn thoát khỏi chương trình?", "", MessageBoxButton.OKCancel);
                                        if (m == MessageBoxResult.OK)
                                        {
                                            // Application.Current.Terminate();
                                            Microsoft.Xna.Framework.Game game = new Microsoft.Xna.Framework.Game();
                                            game.Exit();
                                        }
                                        break;
                                    case 7:
                                        MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                                        marketplaceReviewTask.Show();
                                        break;
                                }
                            }
                        }
                    }
                }
            }

        }

        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            elementRenderer.Render();
            spriteBatch.Begin();
            spriteBatch.Draw(bg, new Vector2(0, 0), new Rectangle(0, 0, 640, 360), Color.White, 0, Vector2.Zero, 4 / 3.0f, SpriteEffects.None, 0);
            for (int i = 0; i <= 7; i++)
            {
                buttonMenu[i].Draw(spriteBatch);
            }
            if (isThanhTich)
            {
                spriteBatch.Draw(bgThanhTich, new Vector2(100, 20), new Rectangle(0, 0, 379, 265),
                                                       Color.White, 0, Vector2.Zero, 1.6f, SpriteEffects.None, 0);
                diemcao.Draw(spriteBatch, font);
            }
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            //spriteBatch.DrawString(font, (DeviceStatus.ApplicationCurrentMemoryUsage / 1024 / 1024).ToString(), new Vector2(300, 300), Color.Red);
            spriteBatch.End();
        }

        private void XacNhan_Click(object sender, RoutedEventArgs e)
        {
            PlayHieuUng("Click", false);
            PlayNhacGame("MapSelect", true);
            CaiDatStoryboard2.Begin();
            CaiDatStoryboard2.Completed += CaiDatStoryboard2_Completed;
        }

        private void CaiDatStoryboard2_Completed(object sender, EventArgs e)
        {
            buttonMenu[1].setTouch(false);
            isCaiDat = false;
        }
        private void inforStoryboard2_Completed(object sender, EventArgs e)
        {
            buttonMenu[5].setTouch(false);
            isInfor = false;
        }

        private void SetNhacButton()
        {
            if (nhacgame)
            {
                PlayHieuUng("Click", false);
                hubat.Visibility = System.Windows.Visibility.Visible;
                hutat.Visibility = System.Windows.Visibility.Collapsed;

            }
            else
            {
                hubat.Visibility = System.Windows.Visibility.Collapsed;
                hutat.Visibility = System.Windows.Visibility.Visible;
            }
            if (nhacnen)
            {
                PlayHieuUng("Click", false);
                nebat.Visibility = System.Windows.Visibility.Visible;
                netat.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                AudioManager.StopSound("MapSelect.ogg");
                nebat.Visibility = System.Windows.Visibility.Collapsed;
                netat.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void hutat_Click(object sender, RoutedEventArgs e)
        {
            nhacgame = true;
            SetNhacButton();
            SaveMusic.write_Music(nhacnen, nhacgame);
        }
        private void hubat_Click(object sender, RoutedEventArgs e)
        {
            nhacgame = false;
            SetNhacButton();
            SaveMusic.write_Music(nhacnen, nhacgame);
        }
        private void netat_Click(object sender, RoutedEventArgs e)
        {
            AudioManager.PlaySound("MapSelect", true);
            nhacnen = true;
            SetNhacButton();
            SaveMusic.write_Music(nhacnen, nhacgame);
        }
        private void nebat_Click(object sender, RoutedEventArgs e)
        {
            nhacnen = false;
            SetNhacButton();
            SaveMusic.write_Music(nhacnen, nhacgame);
        }
        public static void PlayNhacGame(string name, bool repeat)
        {
            AudioManager.StopSounds();
            if (nhacnen)
            {
                AudioManager.PlaySound(name + ".ogg", repeat);
            }
        }
        public static void PlayHieuUng(string name, bool repeat)
        {
            if (nhacgame)
                AudioManager.PlaySound(name + ".ogg", repeat);
        }
        public static void StopNhac(string name)
        {
            AudioManager.StopSound(name + ".ogg");
        }
    }
}